---
title: "How do I access the Kubernetes api from within a pod container"
date: 2019-7-9
categories:
- devops
- kubernetes
tags:
---

<div id="content">
<blockquote>
<p>
<a href="https://stackoverflow.com/questions/30690186/how-do-i-access-the-kubernetes-api-from-within-a-pod-container">https://stackoverflow.com/questions/30690186/how-do-i-access-the-kubernetes-api-from-within-a-pod-container</a>
</p>
</blockquote>
<p>
In the official documentation I found this: 
</p>
<p>
<a href="https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#accessing-the-api-from-a-pod">https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#accessing-the-api-from-a-pod</a>
</p>
<p>
Apparently I was missing a security token that I didn't need in a previous version of Kubernetes. From that, I devised what I think is a simpler solution than running a proxy or installing golang on my container. See this example that gets the information, from the api, for the current container:
</p>
<div class="org-src-container">
<pre class="src src-sh"><span style="font-weight: bold; font-style: italic;">KUBE_TOKEN</span>=$(<span style="font-weight: bold;">cat</span> /var/run/secrets/kubernetes.io/serviceaccount/token)
curl -sSk -H <span style="font-style: italic;">"Authorization: Bearer $KUBE_TOKEN"</span> <span style="font-style: italic;">\</span>
      https://$<span style="font-weight: bold; font-style: italic;">KUBERNETES_SERVICE_HOST</span>:$<span style="font-weight: bold; font-style: italic;">KUBERNETES_PORT_443_TCP_PORT</span>/api/v1/namespaces/default/pods/$<span style="font-weight: bold; font-style: italic;">HOSTNAME</span>
</pre>
</div>
<p>
其中的 KUBERNETES_SERVICE_HOST 和 KUBERNETES_PORT_443_TCP_PORT 来自环境变量。
容器运行时的ServiceAccount Token被挂载到 /var/run/secrets/kubernetes.io/serviceaccount/token 目录
</p>
<p>
访问这些API需要 ServiceAccount 和 Role
<a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">RBAC Authorization</a>
</p>
</div>
<div class="status" id="postamble">
<p class="date">Date: 2019-7-9</p>
<p class="author">Author: amo</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
